﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;

namespace CB.Stock.Core
{
    public interface IValueParser
    {
        object Parse(string value);
    }

    public class GenericValueParser<T> : IValueParser
    {
        #region Implementation of IValueParser<out T>

        public virtual object Parse(string value)
        {
            var cultureInfo = GetSpecialCultureInfo();
            if (cultureInfo == null)
            {
                return (T)(Convert.ChangeType(value, typeof(T)));
            }
            else
            {
                //if the T is double and current culture is EU for example DE
                //then "1.0" of US will "1,0" of DE
                //so derive class should provide the correct culture if needed
                lock (this)
                {
                    var bkC = Thread.CurrentThread.CurrentCulture;
                    try
                    {
                        Thread.CurrentThread.CurrentCulture = cultureInfo;
                        return (T)(Convert.ChangeType(value, typeof(T)));
                    }
                    finally
                    {
                        Thread.CurrentThread.CurrentCulture = bkC;
                    }
                }
            }
        }

        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// override this if special data format provide should be provide
        /// </remarks>
        protected virtual CultureInfo GetSpecialCultureInfo()
        {
            return null;
        }
    }
}
